package cn.dankal.lequ.ui.customview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

import com.zhy.autolayout.AutoFrameLayout;
import com.zhy.autolayout.AutoLinearLayout;

/**
 * Fred
 */

public class SlidingLayout extends AutoLinearLayout {
    public Scroller mScroller;//借助Scroller移动动画
    public boolean isOnTop = false;//分类标题栏是不是处于最顶部s
    public int duration = 400;
    public boolean measured;
    AutoLinearLayout mLinearLayout;
    AutoFrameLayout parentLayout;
    private Context mContext;
    private int offsetY;
    private boolean OnOrignalPlace = true;//是否在初始位置
    private int mTouchSlap;
    private int mdistance, mdistanceX;
    private int origY, origX;
    private int downY, downX, interectY, interectX;
    private boolean isScroll = false;
    private View mTopView;
    private boolean firstPress = true;

    public SlidingLayout(Context context) {
        super(context);
    }

    public SlidingLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(VERTICAL);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        if (!measured) {
            mContext = getContext();
            parentLayout = (AutoFrameLayout) getParent();
            offsetY = parentLayout.getChildAt(0).getMeasuredHeight();

            mLinearLayout = (AutoLinearLayout) getChildAt(0);
            int ParentHeight = getMeasuredHeight();
            mLinearLayout.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ParentHeight));
            mTouchSlap = ViewConfiguration.get(mContext).getScaledTouchSlop();
            mScroller = new Scroller(mContext);
            measured = true;
        }

        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downY = (int) event.getRawY();
                downX = (int) event.getRawX();
                origY = downY;
                origX = downX;
                mdistance = 0;
                mdistanceX = 0;
                if (firstPress) {
                    mLinearLayout.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getMeasuredHeight() + offsetY));
                    firstPress = false;
                }
            case MotionEvent.ACTION_MOVE:
                //没有拉到最上面的时候只能网上偏移
                int dy = downY - (int) event.getRawY();//原先的位置减去当前的位置scrollBy(0, dy);正数上滑，负数下滑
                int dx = downX - (int) event.getRawX();
                mdistanceX = (int) event.getRawX() - origX;
                mdistance = (int) (event.getRawY() - origY);
                if (!isOnTop) {
                    //纵向长于横向距离
                    if (Math.abs(mdistance) > Math.abs(mdistanceX)) {
                        if (mdistance < 0) {
                            //当没有触动布局移动，那么要移动这么长距离才能触发滑动
                            // && Math.abs(mdistance) > 5 * mTouchSlap
                            if (OnOrignalPlace) {
                                scrollBy(0, dy);
                                downY = (int) event.getRawY();
                                downX = (int) event.getRawX();
                                OnOrignalPlace = false;
                                //当布局移动了，跟随着每点的移动
                            } else if (!OnOrignalPlace) {
                                if (Math.abs(mdistance) >= offsetY) {
                                    slideup(offsetY);
                                    isOnTop = true;//不能再移动
                                } else {
                                    scrollBy(0, dy);
                                    downY = (int) event.getRawY();
                                    downX = (int) event.getRawX();
                                }

                            }
                        } else if (mdistance > 0) {
                            if (!OnOrignalPlace) {
                                if (Math.abs(mdistance) >= 0) {
                                    slidedown(mdistance);
                                    downY = (int) event.getRawY();
                                    downX = (int) event.getRawX();
                                    OnOrignalPlace = true;//不能再移动
                                }
                            }
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_UP:

                //如果在上面不允许跟随手势滑下

                if (Math.abs(mdistance) > Math.abs(mdistanceX)) {
                    if (isOnTop) {
                        if (mdistance > 0 && mdistance >= 15 * mTouchSlap) {
                            if (Math.abs(mdistance) > Math.abs(mdistanceX)) {
                                slidedownFromTop();
                            }
                        }
                    }
                    //distance<0，说明了终点始终在起点的上方,最终状态是上拉
                    if (mdistance < 0 && !OnOrignalPlace && !isOnTop) {
                        if (Math.abs(mdistance) <= 10 * mTouchSlap) {
                            slidedown(mdistance);
                        } else {
                            slideup(mdistance);
                        }
                    } else if (mdistance < 0 && OnOrignalPlace) {
                        slideup(mdistance);
                    }

                }
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                interectY = (int) ev.getY();
                interectX = (int) ev.getX();
                isScroll = false;
                break;
            case MotionEvent.ACTION_MOVE:
                //判断如果上下滑就拦截点击事件
                isScroll = Math.abs((int) ev.getY() - interectY) > Math.abs((int) ev.getX() - interectX) && !isOnTop;
                break;
            case MotionEvent.ACTION_UP:
                isScroll = false;
                break;
        }
        return isScroll;
    }

    @Override
    public void computeScroll() {
        //computeScrollOffset判断动画是否完成
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            //这个方法调用computeScroll，这样就陷入循环直至结束
            postInvalidate();
        } else {//动画结束，那么要是后面有点击事件，那么点击事件要执行了
            SlideManager.isOnTop = isOnTop;
        }
        super.computeScroll();
    }


    public void slidedown(int startY) {
        startY = Math.abs(startY);
        mScroller.startScroll(0, startY, 0, -startY, duration);
        invalidate();//刷新界面，才有滚动效果
        OnOrignalPlace = true;
        isOnTop = false;

    }


    /**
     * 第一二个参数是起始点，三四为偏移量(注意不是结束位置的坐标)，最后为时间
     * <p/>
     * startScroll(0, startY, 0, dy, duration);
     * 注意startY方向不要搞错，布局总体往上偏移负方向，那么startY就要是正值
     */
    public void slideup(int startY) {
        if (!isOnTop) {
            startY = Math.abs(startY);
            mScroller.startScroll(0, startY, 0, offsetY - startY, duration);
            invalidate();
            OnOrignalPlace = false;
            isOnTop = true;
        }
    }

    public void slidedownFromTop() {
        slidedown(offsetY);
    }


}
